package com.mycinema.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.mycinema.biz.CategoryBiz;
import com.mycinema.biz.MovieBiz;
import com.mycinema.entity.Category;
import com.mycinema.entity.Movie;

@Controller
public class AjaxController {
	@Autowired
	private MovieBiz movieBiz;
	@Autowired
	private CategoryBiz categoryBiz;

	@RequestMapping("/movie")
	@ResponseBody
	// 将方法的返回值序列化为json视图
	public Movie getMovieById(
			@RequestParam(name = "id", required = false, defaultValue = "1") int id) {
		return movieBiz.getById(id);
	}
	
	@RequestMapping("/movies")
	@ResponseBody
	public List<Movie> getMovies(){
		return movieBiz.getMoviesWithIf(0, null);
	}
	
@RequestMapping("/map")
@ResponseBody
	public Map<String, Object> maps(){
	Map<String, Object>	map =new HashMap<String, Object>();
	map.put("message","json序列化");
	map.put("movie",movieBiz.getById(2));
//	map.put("movies", movieBiz.getMoviesByCid(1));
	return map;
}

	@RequestMapping("/getAllCategories")
	@ResponseBody
	public List<Category> getAll(){
		System.out.println(categoryBiz.getAll());
		return categoryBiz.getAll();
	}

	@RequestMapping("/ajax")
	public String ajax(){
		return "ajax";
	}
	
	@RequestMapping("/saveCate")
	@ResponseBody
	public void save(String name){
		Category category =new Category();
		category.setName(name);
		System.out.println(category.getName());
		categoryBiz.addCategory(category);
		System.out.println("保存成功");
		return;
	}
	
	@RequestMapping(value="/p1",produces={"application/json;charset=UTF-8"}//解决中文乱码
	)
	@ResponseBody//返回出去
	public String p1(){//返回一个值
		Movie movie =movieBiz.getById(1);
		return JSON.toJSONString(movie);
	}
	
	@RequestMapping("/p2")
	@ResponseBody
	public String p2(){//返回一个集合
		List<Movie> list=movieBiz.getMoviesWithIf(1,"");
		String result =JSON.toJSONString(list,true);
		System.out.println(result);
		return result;
	}
	
	@RequestMapping("/p3")
	public Object p3(Model model){
		Movie movie =movieBiz.getById(2);
		model.addAttribute("movie",movie);
		return movie;
	}
}
